<?php



class manageItems {

	var $table='bj_audio';

	var $products=array();

	var $content='';

	var $tblwidth="90%";

	var $page=0;

	var $nrpages=0;

	var $nrows=0;

	var $islist=0;

	

	function manageItems() {

		if(isset($_GET['action']) ) {

			$data=utils::gpc_check($_GET);

			switch($_GET['action']) {

				case 'list' :

					$this->listItems();

					break;

				case 'edit' :

					$this->editItem($data['id']);

					break;

				case 'add' :

					$this->addItem();

					break;

            case 'addbulk' :

                $this->addBulk();

                break;

            case 'addbulkzip':

                $this->addBulkZip();

                break;

				case 'delete' :

					$this->deleteItem($data['id']);

					break;

				default :

					$this->listItems();

			}

		} else {

			$this->listItems();

		}

		$this->tohtml();

	}

  

  function addBulkZip() {

    global $conn;

    if (isset($_GET['upd'])) {

        $data = utils::gpc_check($_POST);

        //var_dump($data);exit;

        foreach ($data['purl'] as $k => $v) {

        

            // if skip option

            $tmpftitle = str_replace(' ', '_', str_replace('.mp3', '', $data['pfile'][$k]));

            if (isset($data['popt'][$tmpftitle]) && (intval($data['popt'][$tmpftitle]) == 0) ) {

                continue;

            } elseif (isset($data['popt'][$tmpftitle]) && (intval($data['popt'][$tmpftitle]) == 1) ) {

                $sql = "UPDATE ";

                $where = " WHERE file_title = '{$tmpftitle}'";

            } else {

                $sql = "INSERT INTO ";

                $where = '';

            }

            

            if (!empty($data['purl'][$k])) {

                $data['ptitle'][$k] = $data['purl'][$k];

            } else {

                $data['ptitle'][$k] = str_replace(' ', '_', str_replace('.mp3', '', $data['pfile'][$k]));

            }

            $sql .= " {$this->table} SET

                  id_parent='{$data['pcat'][$k]}',

                  date_added=NOW(),

                  file_name='{$data['pfile'][$k]}',

                  file_title='{$data['ptitle'][$k]}'

                  {$where}";

                  

            mysql_query($sql, $conn);

            $orig_file = getcwd() . '/tmp/' . $data['ptmpdir'] . '/' . $data['pfile'][$k];

            $dest_file = getcwd() . '/../themesongs/' . $data['pfile'][$k];

            rename($orig_file, $dest_file);

            chmod($dest_file, 0777);

        }

        // delete the unzipped files and remove the temporary directory

        if ( FALSE !== ($hd = opendir(getcwd() . '/tmp/' . $data['ptmpdir'])) ) {

          while (false !== ($file = readdir($hd))) {

              if ($file != '.' && $file != '..') {

                  $f = getcwd() . '/tmp/' . $data['ptmpdir'] . '/' . $file;

                  unlink($f);

              }

          }

        }

        rmdir(getcwd() . '/tmp/' . $data['ptmpdir']);

        

			$this->content='<script language="javascript" type="text/javascript">document.location=\''.PAGE_NAME. '?action=list\';</script>';

			return;

        

    } elseif (isset($_POST['pftp']) || !empty($_FILES['zipfile']) ) {

        $unzipDirName = mktime();

        $tmpDir = getcwd() . '/tmp';

        $unzipTmpDir = $unzipTmpDir = getcwd() . '/tmp/' . $unzipDirName;

        

        if ( !empty($_POST['pftp'])) {

          if (is_readable($tmpDir . '/' . $_POST['pftp'])) {

            $tmpFileName = $tmpDir . '/' . $_POST['pftp'];

          } else {

            die ('The file does not exist or you have entered an incorrect name');

          }

        } else {

          $tmpFileName = $tmpDir . '/' . $_FILES['zipfile']['name'];

          move_uploaded_file($_FILES['zipfile']['tmp_name'], $tmpFileName);

          chmod( $tmpFileName, 0777);

          if (!is_dir($unzipTmpDir)) {

              mkdir ( $unzipTmpDir );

              chmod($unzipTmpDir, 0777);

          }

        }

        //var_dump($tmpFileName);exit;

        exec('unzip ' . $tmpFileName . ' -d ' . $unzipTmpDir, $exec_err);

        //unlink($tmpFileName);

        

        if ( FALSE !== ($hd = opendir($unzipTmpDir)) ) {

        $this->content = '<br><br>

				<form name="frm0" action="'.PAGE_NAME.'?action=addbulkzip&upd" method="post" enctype="multipart/form-data">

            <input type="hidden" name="ptmpdir" value="' . $unzipDirName . '">';

            

            $x = 0;

            $id_parent = (!empty($_GET['id_cat']) ? $_GET['id_cat'] : 0);

            $cats = utils::getpages();

            $array = array();
						while (false !== ($file = readdir($hd))) {
							$array[] = $file;
							sort($array);
						}

            foreach($array as $file) {

                $file_title = str_replace(' ', '_', str_replace('.mp3', '', $file));

                // query the database for duplicates

                $flagd = FALSE;

                $res = mysql_query("SELECT * FROM {$this->table} WHERE file_title='" . str_replace(' ', '_', str_replace('.mp3', '', $file)) . "'");

                if ($res !== FALSE && mysql_num_rows($res)) {

                    $flagd = TRUE;

                    $duplicate = mysql_fetch_assoc($res);

                    mysql_free_result($res);

                }

                

                if ($file != '.' && $file != '..' && substr($file, -3, 3) == 'mp3') {



    				$this->content .= '

    					<tr style="background-color:#bbbbbb;table-layout:fixed">

    						<th colspan="2">Confirm file (' . ($x + 1) . ')</th>

    					</tr>

    					<tr>

    						<td>Category</td>

    						<td>

    							<select name="pcat[]" size="1">

    								<option value="0">--select category--</option>';

      			foreach($cats as $k) {

      				$this->content.='<option value="'.$k[0].'"'.($k[0]==$id_parent ? ' selected':'').'>'.$k[1].'</option>';

      			}

    	  		$this->content.='

    						</select>

    						</td>

    					</tr>

                    <tr>

                        <td>Custom URL</td>

                        <td><input type="text" name="purl[]" size="40" value="' . $file_title . '"></td>

                    </tr>

  					<tr>

  						<td>MP3 file</td>

  						<td><input type="text" disabled value="' . $file . '" size="40"><input type="hidden" name="pfile[]" value="' . $file . '"></td>

  					</tr>';

                if ($flagd) {

                $this->content .= '

                    <tr class="co_error">

                        <td colspan="2" align="center" class="co_error">This URL/file title already exists in the database, and it points to the file &quot;' . htmlspecialchars(stripslashes($duplicate['file_name'])) . '&quot; What would you like to do? <br>

                        <input type="radio" name="popt[' . $file_title . ']" value="0" checked>Skip the newly uploaded song &nbsp;&nbsp;

                        <input type="radio" name="popt[' . $file_title . ']" value="1">Overwrite the existing song&nbsp;&nbsp;

                        <input type="radio" name="popt[' . $file_title . ']" value="2">Import as different song(using same file)*

                        </td>

                    </tr>';

                }

                $this->content .= '<tr><td colspan="2">&nbsp;</td></tr>';

                $x++;

                }

            }

          $this->content .= '

  			<tr height="30">

  				<td colspan="2" align="center">

  					<input type="submit" value="Proceed" class="zrm_button">

  					<input type="button" value="Cancel" class="zrm_button" onclick="document.location=\'' . PAGE_NAME . '?id_cat=' . $id_parent . '\'">

  				</td>

  			</tr>

            <tr>

                <td colspan="2">* When you import the same song using a different title 

                (to generate more links to your site), you will have to make sure you change the TITLE or 

                an error will be issued from the database.</td>

            </tr>';

        fclose($hd);

        }

        

         

    } else {

        $this->content = '<br><br>

          <form name="frmzipupload" actio="' . PAGE_NAME . '?action=addbulkzip" method="post" enctype="multipart/form-data">

            <input type="hidden" name="pcat" value="' . intval($_GET['id_cat']) . '">

            <tr style="background-color:#bbbbbb;table-layout:fixed">

                <th colspan="2">Upload a ZIP compressed file</td>

            </tr>

            <tr>

                <td>ZIP file to upload:</td>

                <td><input type="file" name="zipfile" size="40"></td>

            </tr>

            <tr>

                <td>OR specify a file uploaded by FTP under /admin0/tmp <span class="co_error">(case sensitive)</span></td>

                <td><input type="text" name="pftp" size="40"></td>

            </tr>

            <tr>

                <td align="center" colspan="2"><input type="submit" value="Upload">&nbsp;&nbsp;<input type="button" value="Cancel" onclick="document.location.href=\'./audio_fles.php' . (!empty($_GET['id_cat']) ? '?id_cat=' . $_GET['id_cat'] : '') . '\'">

            </tr>

            <tr><td colspan="2">

                <br>Also recommended: after a bulk zip upload(or a bulk upload) please go to the 

                menu &quot;Google Sitemap&quot; and regenerate + resubmit the sitemap.

                <br><br>When you want to upload a zip archive, first of all navigate to the desired category

                then hit the &quot;Bulk ZIP Upload&quot; button, so that there\'s already a category 

                assigned to your songs, spares some time for setting the category on each item.

                <br><br>Advice: from time to time connect to the FTP and delete everything you will find

                under /admin0/tmp (but don\'t remove that "tmp" dir !!). That is the place where temporary files 

                are being stored during the import and it might happen that not everytime those temporary files

                are deleted (like when you want to import then you hit Cancel, or connection interrupted etc...) 

                </td>

            </tr>

          </form>';

    }

  }



  function addBulk() {

    global $conn;

    if(isset($_GET['upd'])) {

        $data = utils::gpc_check($_POST);



        foreach ($data['purl'] as $k => $v) {

  			if (!empty($_FILES['pfile']['name'][$k])) {

  				$data['pfile'][$k] = mysql_real_escape_string($_FILES['pfile']['name'][$k]);

  				move_uploaded_file($_FILES['pfile']['tmp_name'][$k], ROOT_DIR . 'themesongs/' . $_FILES['pfile']['name'][$k]);

                chmod(ROOT_DIR . 'themesongs/' . $_FILES['pfile']['name'][$k], 0777);

                if (!empty($data['purl'][$k])) {

                    $data['ptitle'][$k] = $data['purl'][$k];

                } else {

                    $data['ptitle'][$k] = str_replace(' ', '_', str_replace('.mp3', '', $_FILES['pfile']['name'][$k]));

                }

                $sql = "INSERT INTO {$this->table} SET

                      id_parent='{$data['pcat'][$k]}',

                      date_added=NOW(),

                      file_name='{$data['pfile'][$k]}',

                      file_title='{$data['ptitle'][$k]}'";

                  mysql_query($sql, $conn) or die(mysql_error());

  			}

        }

			$this->content='<script language="javascript" type="text/javascript">document.location=\''.PAGE_NAME. '?action=list\';</script>';

			return;

        

    } else {

        $id_parent = (!empty($_GET['parent']) ? intval($_GET['parent']) : 0);

        $cats=utils::getpages();

        

        $this->content = '<br><br>

				<form name="frm0" action="'.PAGE_NAME.'?action=addbulk&upd" method="POST" onsubmit="return xsubmit(\'frm0\')" enctype="multipart/form-data">';

            

        for($x = 0; $x < BULK_UPLOAD_ITEMS; $x++) {

				$this->content .= '

					<tr style="background-color:#bbbbbb;table-layout:fixed">

						<th colspan="2">Add MP3 file (' . ($x + 1) . ')</th>

					</tr>

					<tr>

						<td>Category</td>

						<td>

							<select name="pcat[]" size="1">

								<option value="0">--select category--</option>';

  			foreach($cats as $k) {

  				$this->content.='<option value="'.$k[0].'"'.($k[0]==$id_parent ? ' selected':'').'>'.$k[1].'</option>';

  			}

	  		$this->content.='

						</select>

						</td>

					</tr>

                <tr>

                    <td>Custom URL</td>

                    <td><input type="text" name="purl[]" size="40"></td>

                </tr>

					<tr>

						<td>MP3 file</td>

						<td><input type="file" name="pfile[]" size="40"></td>

					</tr>

					<tr height="30">

						<td colspan="2" align="center">

							<input type="submit" value="Add" class="zrm_button">

							<input type="button" value="Cancel" class="zrm_button" onclick="document.location=\''.PAGE_NAME.'\' ">

						</td>

					</tr>

                <tr><td colspan="2">&nbsp;</td></tr>';

        }

        $this->content .= '</form>';

    }

  }

  

	function addItem() {

		global $conn;

		if(isset($_GET['upd'])) {

			$data=utils::gpc_check($_POST);

			

			if (!empty($_FILES['pfile']) ) {

				$data['pfile'] = mysql_real_escape_string($_FILES['pfile']['name']);

				move_uploaded_file($_FILES['pfile']['tmp_name'], ROOT_DIR . 'themesongs/' . $_FILES['pfile']['name']);

            chmod (ROOT_DIR . 'themesongs/' . $_FILES['pfile']['name'], 0777);

			} else {

            die ('No file uploaded');

        }

			

        if (!empty($data['purl'])) {

            $data['ptitle'] = $data['purl'];

        } else {

            $data['ptitle'] = str_replace('.mp3', '', $_FILES['pfile']['name']);

            $data['ptitle'] = str_replace(' ', '_', $data['ptitle']);

        }

        

			$sql = " 

				INSERT INTO {$this->table} SET

                id_parent='{$data['pcat']}',

					date_added=NOW(),

					file_name='{$data['pfile']}',

                file_title='{$data['ptitle']}'

				";

			mysql_query($sql,$conn) or die(mysql_error());

			$data['uid'] = mysql_insert_id($conn);

        mysql_query("INSERT INTO traffic_stats SET id_item={$data['uid']}");

			

			//$this->regenerateXML();



			$this->content='<script language="javascript" type="text/javascript">document.location=\''.PAGE_NAME. '?id_cat=' . $data['pcat'] . '\';</script>';

			return;

		} else {

            $id_parent = (!empty($_GET['parent']) ? intval($_GET['parent']) : 0);

            $cats=utils::getpages();

				$this->content='<br><br>

				<form name="frm0" action="'.PAGE_NAME.'?action=add&upd" method="POST" onsubmit="return xsubmit(\'frm0\')" enctype="multipart/form-data">

					<tr style="background-color:#bbbbbb;table-layout:fixed">

						<th colspan="2">Add MP3 file</th>

					</tr>

					<tr>

						<td>Category</td>

						<td>

							<select name="pcat" size="1">

								<option value="0">--select category--</option>';

  			foreach($cats as $k) {

  				$this->content.='<option value="'.$k[0].'"'.($k[0]==$id_parent ? ' selected':'').'>'.$k[1].'</option>';

  			}

	  		$this->content.='

						</select>

						</td>

					</tr>

                <tr>

                    <td>Custom URL</td>

                    <td><input type="text" name="purl" size="40"></td>

                </tr>

					<tr>

						<td>MP3 file</td>

						<td><input type="file" name="pfile" size="40"></td>

					</tr>

					<tr height="30">

						<td colspan="2" align="center">

							<input type="submit" value="Add" class="zrm_button">

							<input type="button" value="Cancel" class="zrm_button" onclick="document.location=\''.PAGE_NAME.'\' ">

						</td>

					</tr>

				</form>';

            $this->content .= <<<AAA

			<script type="text/javascript">

				addfields("frm0");

				addoblig("frm0",new Array("pcat","pfile"));

			</script>

AAA;

		}

	}



	function deleteItem ($id) {

		global $conn;

		$res = mysql_query("SELECT file_name FROM {$this->table} WHERE id_file={$id}", $conn) or die(mysql_error());

		if( $res !== FALSE && mysql_num_rows($res)) {

			$lin = array_map('stripslashes', mysql_fetch_assoc($res));

			unlink ( ROOT_DIR . 'themesongs/' . $lin['file_name'] );

			mysql_query("DELETE FROM {$this->table} WHERE id_file='{$id}'", $conn);

        mysql_query("DELETE FROM traffic_stats WHERE id_item='{$id}'", $conn);

		}

		

		//$this->regenerateXML();

		

		$this->content='<script type="text/javascript">document.location=\'' . PAGE_NAME. '\';</script>';

		return;

	}

	

	function editItem($id) {

		global $conn;

		if(isset($_GET['upd'])) {

			$data=utils::gpc_check($_POST);

			

			$sql = "UPDATE {$this->table} SET id_parent='{$data['pcat']}'";

                

			if (!empty($_FILES['pfile']['tmp_name']) ) {

				move_uploaded_file($_FILES['pfile']['tmp_name'], ROOT_DIR . 'themesongs/' . $_FILES['pfile']['name']);

            chmod (ROOT_DIR . 'themesongs/' . $_FILES['pfile']['name'], 0777);

            $data['ptitle'] = str_replace('.mp3', '', $_FILES['pfile']['name']);

            $data['ptitle'] = str_replace(' ', '_', $data['ptitle']);

            if (!empty($data['purl'])) {

                $data['ptitle'] = $data['purl'];

            }

    		$data['pfile'] = mysql_real_escape_string($_FILES['pfile']['name']);

				$sql .= ",file_name='{$data['pfile']}',file_title='{$data['ptitle']}'";

			} elseif (!empty($data['purl'])) {

            $sql .= ",file_title='{$data['purl']}'";

        }

			

			$sql .=" WHERE id_file={$id}";

			mysql_query($sql,$conn) or die(mysql_error());

			$data['uid'] = $id;

			

			//$this->regenerateXML();

			

			$this->content='<script type="text/javascript">document.location=\''.PAGE_NAME.'?id_cat=' . $data['pcat'] . '\';</script>';

			return;

		} else {

			$this->tblwidth="70%";

        $cats=utils::getpages();

			$sql = " SELECT * FROM {$this->table} WHERE {$this->table}.id_file='{$id}' ";

			$res=mysql_query($sql, $conn);

			if($res!=FALSE && mysql_num_rows($res)!=0) {

				$lin= array_map('htmlspecialchars', array_map('stripslashes', mysql_fetch_assoc($res)));

				mysql_free_result($res);

				$this->content='<br><br>

				<form name="frm0" action="'.PAGE_NAME.'?action=edit&upd&id=' . $id . ' " method="POST" onsubmit="return xsubmit(\'frm0\')" enctype="multipart/form-data">

					<tr style="background-color:#bbbbbb;table-layout:fixed">

						<th colspan="2">Edit file</th>

					</tr>

					<tr>

						<td>Category</td>

						<td>

							<select name="pcat" size="1">

								<option value="0">--select category--</option>';

  			foreach($cats as $k) {

  				$this->content.='<option value="'.$k[0].'"'.($k[0]==$lin['id_parent'] ? ' selected':'').'>'.$k[1].'</option>';

  			}

	  		$this->content.='

						</select>

						</td>

					</tr>

                <tr>

                    <td>Custom URL</td>

                    <td><input type="text" name="purl" size="40" value="' . $lin['file_title'] . '"></td>

                </tr>

					<tr>

						<td>MP3 file</td>

						<td><input type="file" name="pfile" size="40"><br>' . $lin['file_name'] . '</td>

					</tr>

					<tr height="30">

						<td colspan="2" align="center">

							<input type="submit" value="Update" class="zrm_button">

							<input type="button" value="Cancel" class="zrm_button" onclick="document.location=\''.PAGE_NAME.'?id_cat=' . $lin['id_parent'] . '\' ">

						</td>

					</tr>

				</form>';

          $this->content .= <<<AAA

			<script type="text/javascript">

				//addfields("frm0");

				//addoblig("frm0",new Array("ptitle"));

			</script>

AAA;

			}

		}

	}

		



	function listItems($order='date_added DESC') {

		global $conn;

		unset($this->cats);

		$this->tblwidth="95%";

		$where=' WHERE 1';

		$this->islist=1;

		

		$this->page=(isset($_SESSION['cpage'])?$_SESSION['cpage']:0);

		if(isset($_GET['nav'])) {

			$_SESSION['cpage']=$_GET['nav']-1;

		} else {

			$_SESSION['cpage']=0;

		}

		$this->page=$_SESSION['cpage'];

		

		if(!empty($_GET['criteria'])) {

			$where.=" AND UPPER(file_name) LIKE '%".strtoupper(urldecode($_GET['criteria']))."%'";

		}

    if (!empty($_GET['id_cat'])) {

        $where .= " AND {$this->table}.id_parent=" . intval($_GET['id_cat']); 

    }



		$sql="SELECT COUNT(*) FROM {$this->table} ".$where;

		$res=mysql_query($sql,$conn);

		if($res!=FALSE && mysql_num_rows($res)!=0) {

			$lin=mysql_fetch_row($res);

			mysql_free_result($res);

			$this->nrpages=ceil($lin[0]/ROWS_PER_PAGE);

		} else {

			$this->nrpages=0;

		}

		

		$startfrom = $this->page*ROWS_PER_PAGE;

		$sql="

			SELECT {$this->table}.*,pages.page_name

			FROM {$this->table}

        LEFT JOIN pages ON {$this->table}.id_parent=pages.id_category

			{$where}

			ORDER BY {$order}

			LIMIT {$this->page}, ".ROWS_PER_PAGE;

		$res=mysql_query($sql,$conn) or die(mysql_error());

		if($res!=FALSE && mysql_num_rows($res)>0) {

			while($lin=mysql_fetch_assoc($res)) {

				$this->products[]=$lin;

			}

			$this->nrows=mysql_num_rows($res);

			mysql_free_result($res);

		}

		

		$this->content='

				<tr style="background-color:#bbbbbb;">

					<th>

						<a href="' . PAGE_NAME . '?action=list&amp;order=file_title" class="header">URL</a>

					</th>

					<th>

						<a href="' . PAGE_NAME . '?action=list&amp;order=file_name" class="header">Filename</a>

					</th>

                <th>Category</th>

					<th width="10%">Actions</th>

				</tr>

			';

		if($this->nrows>0) {

			foreach($this->products as $k=>$v) {

				$this->content.='

					<tr >

						<td align="left">

							<a href="' . utils::create_href($v['file_title']) . '" target="_blank">' . $v['file_title'] . '</a>

						</td>

						<td>

							' . htmlspecialchars(stripslashes($v['file_name'])) . '

						</td>

                    <td align="center"><b>' . stripslashes($v['page_name']) . '</b></td>

						<td align="center">

							<a href="'.PAGE_NAME.'?action=edit&amp;id='.$v['id_file'].'"><img src="./images/edit.gif" border="0" alt="Modify"></a>&nbsp;

							<a href="'.PAGE_NAME.'?action=delete&amp;id='.$v['id_file'].'"><img src="./images/delete.gif" border="0" alt="Delete" onclick="if(confirm(\'Are you sure you want to delete this file?\')==true) return true; else return false"></a>&nbsp;

						</td>

					</tr>';

			}

		}

	}

	

	function tohtml() {

		$content='';

		$cats=utils::getpages();

    $id_cat = (!empty($_GET['id_cat']) ? intval($_GET['id_cat']) : 0);



		if($this->islist) {

		$content.='

    <br>

		<form name="dispay" method="get" action="'.PAGE_NAME.'">

    <table width="' . $this->tblwidth . '" cellpadding="0">

        <tr>

            <td>Show songs in category:

                <select name="id_cat" size="1" onchange="this.form.submit();">

                    <option value="0">Show all</option>';

  	foreach($cats as $k) {

  		$content.='<option value="'.$k[0].'"'.($k[0]==$id_cat ? ' selected':'').'>'.$k[1].'</option>';

  	}

    $content .= '

                </select>

            </td>

        </tr>

    </table>

		<table border="0" cellpadding="2" cellspacing="1" width="'.$this->tblwidth.'" style="border-collapse:collapse;margin-top:20px;table-layout:auto" align="center">

		<tr>

			<td>

            <input type="button" value="Add File" class="zrm_button" onclick="document.location=\''.PAGE_NAME.'?action=add\'">&nbsp;&nbsp;

            <input type="button" value="Bulk Upload" class="zrm_button" onclick="document.location=\''.PAGE_NAME.'?action=addbulk\'">&nbsp;&nbsp;

            <input type="button" value="Bulk ZIP Upload" class="zrm_button" onclick="document.location=\''.PAGE_NAME.'?action=addbulkzip&id_cat=' . (isset($_GET['id_cat']) ? $_GET['id_cat'] : 0) . '\'">

        </td>

		</tr>

		</table>

		</form>';

		}

		$content.='<table border="1" cellpadding="3" cellspacing="1" width="'.$this->tblwidth.'" style="border-collapse:collapse;" align="center">';

			

		$content.=$this->content;	

		$content.='</table>';

		echo $content;

	}	

	

	

} 

?>